package com.traffic.between.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;
import com.google.gson.JsonObject;
import com.traffic.between.config.BetweenProperties;


public class BaiMiaoServiceImpl {
	private static Logger logger = Logger.getLogger(BaiMiaoServiceImpl.class);
	public static BaiMiaoServiceImpl service = new BaiMiaoServiceImpl();
	
	private static String HOST_ORDER_PATH =BetweenProperties.BAIMIAO_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH =BetweenProperties.BAIMIAO_ORDERSTATUS_URL;
	private static String BAIMIAO_PLATFORMID = BetweenProperties.BAIMIAO_PLATFORMID;
	private static String BAIMIAO_SECURITY =BetweenProperties.BAIMIAO_SECURITY;
	
	
	
	public String order(String pkgNo, String phoneNo, String tradeNo,String callbackURL) {
		

		StringBuffer stringBuffer = new StringBuffer();
		try{
			String strtmpproduct = encrypt(pkgNo,BAIMIAO_SECURITY);
			String strtmpmobile = encrypt(phoneNo,BAIMIAO_SECURITY);
			String strtimestamp = Long.toString((long) (System.currentTimeMillis()));
			String struserno = BAIMIAO_PLATFORMID+strtimestamp;
			Map<String, String> cloudmap = new HashMap<String,String>();	
			cloudmap.put("mobile", phoneNo);
			cloudmap.put("userorderno", struserno);
			cloudmap.put("timestamp", strtimestamp);				
			cloudmap.put("productid", pkgNo);
			cloudmap.put("platformid",BAIMIAO_PLATFORMID);
			cloudmap.put("security",BAIMIAO_SECURITY);
			String sourceStr = createLinkString(cloudmap);		
			
			String signaturecheck = getMD5(sourceStr);

			JsonObject jo = new JsonObject();
			jo.addProperty("mobile", strtmpmobile);
			jo.addProperty("effecttype", "0");
			jo.addProperty("userorderno", struserno);
			jo.addProperty("timestamp", strtimestamp);
			jo.addProperty("productid", strtmpproduct);
			jo.addProperty("sign", signaturecheck);
			jo.addProperty("cburl", URLEncoder.encode(callbackURL));
			
			logger.info("百妙骏业的订购请求参数:"+jo.toString()+",该订单号为："+tradeNo);
			URL url = new URL(HOST_ORDER_PATH);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			//connection.setDoInput(true);
			connection.setDoOutput(true);       
			String tmpplatformid = "platformid="+"\""+BAIMIAO_PLATFORMID+"\"";
			connection.setRequestProperty("Authorization", tmpplatformid);
			connection.setRequestProperty("Accept","application/json;charset=UTF-8");
			connection.setRequestProperty("Content-Type","application/json");

			// Post 请求不能使用缓存    
			connection.setUseCaches(false);   
			connection.setConnectTimeout(30 * 1000);
			connection.setReadTimeout(60 * 1000);
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
			out.write(jo.toString());
			out.flush();
			out.close();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String responseLine = "";

			while((responseLine = reader.readLine()) != null) {
				stringBuffer.append(responseLine);
			}
			logger.info("百妙骏业的订购返回信息:"+stringBuffer.toString()+",该订单号为："+tradeNo);
		}catch(Exception e){
			logger.info("百妙骏业订购请求异常："+e.getMessage()+",该订单号为："+tradeNo);
		}
		return stringBuffer.toString();
	}

	
	
	
	public String orderStatus(String cstmOrderNo) {
		
		
		StringBuffer stringBuffer = new StringBuffer();
		try{
			String strtimestamp = Long.toString((long) (System.currentTimeMillis()));
			Map<String, String> cloudmap = new HashMap<String,String>();	
			cloudmap.put("timestamp", strtimestamp);				
			cloudmap.put("userorderno", cstmOrderNo);
			cloudmap.put("platformid",BAIMIAO_PLATFORMID);
			cloudmap.put("security",BAIMIAO_SECURITY);
			String sourceStr = createLinkString(cloudmap);		
					
			String signaturecheck = getMD5(sourceStr);

			JsonObject jo = new JsonObject();
			jo.addProperty("timestamp", strtimestamp);
			jo.addProperty("userorderno", cstmOrderNo);
			jo.addProperty("sign", signaturecheck);
			logger.info("百妙骏业的查询请求信息:"+jo.toString());
			URL url = new URL(HOST_ORDERSTATUS_PATH);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			//connection.setDoInput(true);
			connection.setDoOutput(true);       
			String tmpplatformid = "platformid="+"\""+BAIMIAO_PLATFORMID+"\"";
			connection.setRequestProperty("Authorization", tmpplatformid);
			connection.setRequestProperty("Accept",  "application/json;charset=UTF-8");
			connection.setRequestProperty("Content-Type","application/json");

			// Post 请求不能使用缓存    
			connection.setUseCaches(false);  
			connection.setConnectTimeout(30 * 1000);
			connection.setReadTimeout(60 * 1000);
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
			out.write(jo.toString());
			out.flush();
			out.close();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String responseLine = "";

			while((responseLine = reader.readLine()) != null) {
				stringBuffer.append(responseLine);
			}
			logger.info("百妙骏业的查询返回信息:"+stringBuffer.toString()+",该订单号为："+cstmOrderNo);
		}catch(Exception e){
			logger.info("百妙骏业查询请求异常："+e.getMessage()+",该订单号为："+cstmOrderNo);
		}
		return stringBuffer.toString();
	}

	
	
	public static  String createLinkString(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}
		return prestr;
	}

	/**
	 * Description 根据键值进行加密
	 * @param data 
	 * @param key  加密键byte数组
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data, String key) throws Exception {
		byte[] bt = encrypt(data.getBytes(), key.getBytes());
		String strs = new BASE64Encoder().encode(bt);
		return strs;
	}
	
	/**
	 * Description 根据键值进行加密
	 * @param data
	 * @param key  加密键byte数组
	 * @return
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();

		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);

		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance("DES");

		// 用密钥初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toUpperCase();
	}

	public static void main(String[] args) {
	    //String reString = new BaiMiaoServiceImpl().order("LT01000050", "18566783696", "", "");
	   // System.out.println(reString);
		String reString = new BaiMiaoServiceImpl().orderStatus("ceshi1499077957686");
		System.out.println(reString);
	}
}
